import { Component, OnInit } from '@angular/core';
import { ServiceQueryService } from "./service-query.service";
import { PaginationModel } from 'app/widgets/pagination';
import { environment } from '../../../../environments/environment';
import { DataService } from '../../../services/data.service';
import * as _ from 'lodash';

@Component({
  selector: 'app-service-query',
  templateUrl: './service-query.component.html',
  styleUrls: ['./service-query.component.scss'],
  providers: [ServiceQueryService]
})
export class ServiceQueryComponent implements OnInit {
  // lodash
  public _: any = _;

  // 菜单数据
  public menuData: any;
  // 菜单权限set
  public menuResourceSet: any = [];
  // 备案机构、受托人、托管人
  public distionary: any = {
    RECORDORG_TYPE: [],  // 备案机构
    LINK_PRINCIPAL_NO: [],   //受托人
    TRUSTEE: []   //  托管人
  }
  // 字典值
  public dictionaryList: any = {
    // LINK_PRINCIPAL_NO: []
  };
  // 服务条目列表数据
  public queryList: any;
  // 服务条目列表全选
  public isCheckedAll: any = false;
  // 服务条目列表请求体
  public getQueryPost = {
    pageIndex: 1,
    pageSize: 10,
    sTrustee: '',
    sIsTemplate: '',
    sFullName: '',
    sFundCode: ''
  };
  // 服务条目列表页配置
  public queryPageInfo: PaginationModel = {
    currentPageNum: 1,
    pageSize: 10,
    totalPages: 1,
    total: 0,
    pagesShow: 5,
    startRow: 0,
    endRow: 0,
    pageList: [5, 10, 25, 50, 100]
  };
  constructor(
    public serviceQueryService: ServiceQueryService,
    public dataService: DataService,
  ) { }

  ngOnInit() {
    let that = this;
    // 字典值
    this.dictionaryList = JSON.parse(localStorage.getItem("dictionaryList"));
    this.getDictionary();
    this.getQueryList();
    // 权限处理
    this.dataService.initTree.subscribe(data => {
      if (data) {
        let SessionMenuData = sessionStorage.getItem('menu');
        this.menuData = JSON.parse(SessionMenuData);
        this.menuResourceSet = [];
        _.forEach(this.menuData, (item, index) => {
          if (item.sName == '条目管理') {
            _.forEach(item.children, (it, idx) => {
              if (it.sName == '服务类条目查询') {
                that.menuResourceSet = it.resourceSet;
                sessionStorage.setItem('btn-entry', this.menuResourceSet);
              }
            })
          }
        })
      }
    })
    let SessionMenuData = sessionStorage.getItem('menu');
    this.menuData = JSON.parse(SessionMenuData);
    this.menuResourceSet = [];
    _.forEach(this.menuData, (item, index) => {
      if (item.sName == '条目管理') {
        _.forEach(item.children, (it, idx) => {
          if (it.sName == '服务类条目查询') {
            that.menuResourceSet = it.resourceSet;
            sessionStorage.setItem('btn-entry', this.menuResourceSet);
          }
        })
      }
    })
  }
  ngAfterViewInit() {
    let that = this;
    setTimeout(function () {
      // 受托人
      window['$']('#entrysTrusteeSelected').select2({ width: '190px', tags: true });
      window['$']('#entrysTrusteeSelected').on("select2:select", function (e) {
        that.getQueryPost.sTrustee = window['$']('#entrysTrusteeSelected').select2("val");
      })
    }, 100);

  }
  // 服务条目列表
  getQueryList(pageNum?, pageSize?) {
    let that = this;
    this.isCheckedAll = false;
    this.getQueryPost.sTrustee = _.trim(this.getQueryPost.sTrustee);
    this.getQueryPost.pageIndex = pageNum ? pageNum : this.queryPageInfo.currentPageNum;
    this.getQueryPost.pageSize = pageSize ? pageSize : this.queryPageInfo.pageSize;
    this.serviceQueryService.getQueryList(this.getQueryPost).subscribe(data => {
      if (data) {
        that.queryList = data.list;
        that.queryPageInfo.currentPageNum = data.pageNum;
        that.queryPageInfo.totalPages = data.pages;
        that.queryPageInfo.total = data.total;
        that.queryPageInfo.startRow = data.startRow;
        that.queryPageInfo.endRow = data.endRow;
      }
    });
  }
  // 服务条目个数分页
  querypageSizeChange(pageSize: number) {
    if (pageSize !== this.queryPageInfo.pageSize) {
      this.queryPageInfo.pageSize = pageSize;
      this.getQueryList();
    }
  }
  // 服务条目条数分页
  queryPageNavigation(currentPageNum: number) {
    this.queryPageInfo.currentPageNum = currentPageNum;
    this.getQueryList(this.queryPageInfo.currentPageNum, this.queryPageInfo.pageSize);
  }
  // 服务条目列表全选
  queryCheckedAll() {
    if (this.isCheckedAll) {
      _.forEach(this.queryList, item => {
        item.isChecked = true;
      });
    } else {
      _.forEach(this.queryList, item => {
        item.isChecked = false;
      });
    }
  }
  // 服务条目列表是否全选
  ctrlQueryCheckAll() {
    let that = this;
    let checkList = [];
    _.forEach(this.queryList, item => {
      if (item.isChecked == true) {
        checkList.push(item);
      }
    })
    if (checkList.length == this.queryList.length) {
      this.isCheckedAll = true;
    } else {
      this.isCheckedAll = false;
    }
  }
  // 导出
  exportExcel() {
    let that = this;
    let checkedItem = [];
    _.forEach(this.queryList, item => {
      if (item.isChecked) {
        checkedItem.push(item.nSerItemNo);
      }
    })
    let converItem: any = checkedItem.join(',');
    let getBody = {
      "nSerItemNoList": converItem,
      "sTrustee": this.getQueryPost.sTrustee,
      "sIsTemplate": this.getQueryPost.sIsTemplate,
      "sFullName": this.getQueryPost.sFullName,
      "sFundCode": this.getQueryPost.sFundCode
    }
    const iframe = window['$']("<iframe id='downloadiframe'>");
    iframe.attr('style', 'display:none');
    //  转码，兼容ie
    getBody.sTrustee = encodeURI(getBody.sTrustee)
    iframe.attr('src', environment.server + '/pms/v1/item/serItem/export/serItem?token=' + sessionStorage.getItem('token') + '&nSerItemNoList=' + getBody.nSerItemNoList + '&sTrustee=' + getBody.sTrustee + '&sIsTemplate=' + getBody.sIsTemplate + '&sFundCode=' + getBody.sFundCode + '&sFullName=' + getBody.sFullName);
    window['$']('body').append(iframe);
    setTimeout("$('#downloadiframe').remove()", 60000);
  }
  // 获取备案机构、受托人、托管人下拉框值
  getDictionary() {
    let that = this;
    this.serviceQueryService.getDictionary().subscribe(data => {
      if (data) {
        that.distionary.RECORDORG_TYPE = data.RECORDORG_TYPE;
        that.distionary.LINK_PRINCIPAL_NO = data.LINK_PRINCIPAL_NO;
        that.distionary.TRUSTEE = data.TRUSTEE;
      }
    })
  }
  // 点击表格头排序
  orderData(colName) {
    let listDataAsc = _.orderBy(this.queryList, [colName], ["asc"]);
    if (JSON.stringify(this.queryList) == JSON.stringify(listDataAsc)) {
      listDataAsc = _.orderBy(this.queryList, [colName], ["desc"]);
    }
    this.queryList = listDataAsc;
  }
}
